package com.customization.unionpay.market.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.service.MarketAdvancePayWorkflowService;
import weaver.backup.logging.Logger;
import weaver.backup.logging.LoggerFactory;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class MarketAdvancePayWorkflowServiceImpl implements MarketAdvancePayWorkflowService {

    private  static final Logger log = LoggerFactory.getLogger(MarketAdvancePayWorkflowServiceImpl.class);


    @Override
    public List<JSONObject> checkBudget(String action, RequestInfo requestInfo) {
        try {
            int requestid = requestInfo.getRequestManager().getRequestid();
            //获取主表数据
            Map<String,Object> map = com.customization.unionpay.market.util.FormDataUtils.getMainFormData(requestInfo);
            //项目编码
            String xmbm = Util.null2String(map.get("project_code"));
            //预算控制期
            String yskzq = Util.null2String(map.get("yskzq"));
            //表单号
            String bdh = Util.null2String(map.get("bdh"));
            //业务类型
            String ywlx = Util.null2String(map.get("ywlx"));
            //申请人
            String sqr = Util.null2String(map.get("sqr"));
            //报账公司
            String bzgs = Util.null2String(map.get("bzgs"));
            //报账部门
            String bzbm = Util.null2String(map.get("bzbm"));
            //入账日期
            String rzrq = Util.null2String(map.get("rzrq"));
            //说明
            String sm = Util.null2String(map.get("bzsy"));
            // 获取业务类型的中文名称
            List<JSONObject> ywlxName = com.customization.unionpay.market.util.FormDataUtils.getItemInfo(requestInfo.getRequestManager().getFormid(),
                    "ywlx", null, ywlx);
            if (CollectionUtil.isEmpty(ywlxName)) {
                log.error("业务类型为空");
                return null;
            }

            //获取申请人名称
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String sqrName = resourceComInfo.getLastname(sqr);
            //获取部门的名称
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            String bzbmName = departmentComInfo.getDepartmentname(bzbm);
            //获取公司的名称
            SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
            String bzgsName = subCompanyComInfo.getSubCompanyname(bzgs);
            //获取明细表数据
            DetailTable tableInfo = requestInfo.getDetailTableInfo().getDetailTable(0);
            List<Map<String,Object>>  jjsxList = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(0,requestInfo);
            if (CollectionUtil.isEmpty(jjsxList)) {
                log.error("预付款单明细表数据为空");
                return null;
            }

            List<JSONObject> list = new ArrayList<>();
            for (Map<String, Object> jjsx : jjsxList) {

                JSONObject rowData = new JSONObject();
                //预算责任中心
                rowData.put("yszrzx",Util.null2String(jjsx.get("yszrzx")));
                //预算科目
                rowData.put("yskm",Util.null2String(jjsx.get("yskm")));
                //预付金额
                rowData.put("yfje",Util.null2String(jjsx.get("yfje")));
                //经济事项
                rowData.put("jjsx",Util.null2String(jjsx.get("jjsx")));
                list.add(rowData);
            }
            //预算占用请求列表
            List<JSONObject> budgetOccupyRequests = new ArrayList<>();
            //调用预算接口
            for (JSONObject rowData : list) {
                JSONObject jsonObject = new JSONObject();
                //预算项目
                jsonObject.put("budgetItem", xmbm);
                //预算科目
                jsonObject.put("budgetAccount", rowData.getString("yskm"));
                //预算责任中心
                jsonObject.put("exeUnit", rowData.getString("yszrzx"));
                //预算期间(年)
                jsonObject.put("budgetPeriod", yskzq.substring(0, 4));
                //金额
                jsonObject.put("amount", Double.parseDouble(rowData.getString("yfje"))/1000);
                //操作
                jsonObject.put("instruction", action);
                //已占据单号(预付申请   执行单据号传requestID  被占用单据号传项目编号)
                jsonObject.put("occDocNo",xmbm);
                //执行单据号
                jsonObject.put("exeDocNo", requestid);
                //预算控制期
                jsonObject.put("budgetPostingPeriod", yskzq);
                //执行日期(当前日期)
                jsonObject.put("executionDate", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
                //执行单据类型
                jsonObject.put("exeDocType", ywlxName.get(0).getString("name"));
                //报账人
                jsonObject.put("claimant", sqrName);
                //来源系统
                jsonObject.put("sourceSystem", "智慧财务平台");
                //说明
                jsonObject.put("remark", sm);
                //报账部门
                jsonObject.put("reimbursementDept", bzbmName);
                //报账公司
                jsonObject.put("reimbursementCompany", bzgsName);
                //经济事项
                jsonObject.put("economicEvent", rowData.getString("jjsx"));
                //事项
                jsonObject.put("event", "");
                budgetOccupyRequests.add(jsonObject);
            }
            return budgetOccupyRequests;
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public List<JSONObject> executeBudget(String action, RequestInfo requestInfo) {
        try {
            RequestManager rm = requestInfo.getRequestManager();
            int formId = rm.getFormid();
            //获取主表数据
            Map<String,Object> map = com.customization.unionpay.market.util.FormDataUtils.getMainFormData(requestInfo);
            //获取经济事项明细表数据
            List<Map<String,Object>> jjsxList = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(0,requestInfo);
            //获取核销预付款明细表数据
            List<Map<String,Object>> hxypkList = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(2,requestInfo);
            //获取发票信息明细表数据
            List<Map<String,Object>> fpxxList = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(3,requestInfo);
            //项目编码
            String xmbm = Util.null2String(map.get("PROJECT_CODE"));
            //预算控制期
            String yskzq = Util.null2String(map.get("yskzq"));
            //业务类型
            String ywlx = Util.null2String(map.get("ywlx"));
            //业务类型名称
            String ywlxName = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId,"ywlx", ywlx);
            //申请人
            String sqr = Util.null2String(map.get("sqr"));
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String sqrName = resourceComInfo.getWorkcode(sqr);
            //报账公司
            String bzgs = Util.null2String(map.get("bzgs"));
            SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
            String bzgsName = subCompanyComInfo.getSubCompanyname(bzgs);
            //报账部门
            String bzbm = Util.null2String(map.get("bzbm"));
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            String bzbmName = departmentComInfo.getDepartmentname(bzbm);
            //入账日期
            String rzrq = Util.null2String(map.get("rzrq"));
            //说明
            String sm = "";
            //本次核销预付金额合计
            float bchxyfjehj = map.get("bchxyfjehj") == null ? 0 : (float)map.get("bchxyfjehj");

            List<JSONObject> requests = new ArrayList<>();

            for (int i = 0; i < jjsxList.size(); i++) {

                JSONObject jsonObject = new JSONObject();
                Map<String,Object> jjsx = jjsxList.get(i);
                Map<String,Object> hxyfk = hxypkList.get(i);

                float jtye = (float)jjsx.get("jtye");
                //如果计提余额大于0
                if(jtye > 0){
                    //若【本次核销预付金额】≤【合同计提余额】，流程审批通过，不进行预算占用转执行；
                    float htjtye = (float)jjsx.get("htjtye");
                    if(bchxyfjehj <= htjtye){
                        return  new ArrayList<>();
                    }else {
                      jsonObject.put("amount",bchxyfjehj-htjtye);
                    }
                }else {
                    jsonObject.put("amount",bchxyfjehj);
                }
                //预算项目
                jsonObject.put("budgetItem", xmbm);
                //预算科目
                jsonObject.put("budgetAccount", jjsx.get("yskm"));
                //预算责任中心
                jsonObject.put("exeUnit", jjsx.get("yszrzx"));
                //预算期间(年)
                jsonObject.put("budgetPeriod", rzrq.substring(0, 4));
                //操作
                jsonObject.put("instruction", action);
                //执行单据号
                jsonObject.put("exeDocNo", hxyfk.get("bdh"));
                //预算控制期
                jsonObject.put("budgetController", rzrq);
                //执行单据类型
                jsonObject.put("exeDocType", ywlxName);
                //报账人
                jsonObject.put("claimant",sqrName);
                //来源系统
                jsonObject.put("sourceSystem", "智慧财务平台");
                //说明
                jsonObject.put("remark", sm);
                //报账部门
                jsonObject.put("reimbursementDept", bzbmName);
                //报账公司
                jsonObject.put("reimbursementCompany", bzgsName);
                //经济事项
                jsonObject.put("economicEvent",jjsx.get("jjsx"));
                requests.add(jsonObject);
            }
            return requests;
        }catch (Exception e){
             log.error("解析营销预付款核销流程失败");
        }
        return null;
    }

    @Override
    public List<JSONObject> accountingVoucher(RequestInfo requestInfo) {
        try{
            MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
            Map<String,Object> requestMainTableInfo = com.customization.unionpay.market.util.FormDataUtils.getMainFormData(requestInfo);
            //账套号
            String zth = (String) requestMainTableInfo.get("zth");
            //入账日期
            String rzrq = (String) requestMainTableInfo.get("rzrq");
            //表单号
            String bdh = (String) requestMainTableInfo.get("bdh");
            //申请人
            String sqr = (String) requestMainTableInfo.get("sqr");
            //报账公司
            String bzgs = (String) requestMainTableInfo.get("bzgs");
            //报账部门
            String bzbm = (String) requestMainTableInfo.get("bzbm");
            //活动名称
            String hdmc = (String) requestMainTableInfo.get("ACT_NM");
            //供应商编码
            String gysbh = (String) requestMainTableInfo.get("gysbh");
            //合同编码
            String htbh = (String) requestMainTableInfo.get("htbh");

            //获取经济事项明细
            List<Map<String,Object>> jjsx = com.customization.unionpay.market.util.FormDataUtils.getDetailFormDataByIndex(0,requestInfo);
            //获取支付明细
            List<Map<String,Object>> zfmx = FormDataUtils.getDetailFormDataByIndex(1,requestInfo);
            List<JSONObject> requests = new ArrayList<>();
            //获取经济事项明细部分数据
            //获取支付明细部分数据
            //TODO 暂不开发等会计引擎配置
        }catch (Exception e){

        }
        return null;
    }
}
